﻿using System;

namespace cz.zcu.PreSti.Components
{
    public class NormalDistributionGenerator : BaseComponent
    {
        private Random r;
        private double mean = 0;
        private double variance = 1;
        private double cropSize = 0;

        #region properties

        public double Mean
        {
            set
            {
                mean = value;
            }
            get
            {
                return mean;
            }
        }

        public double Variance
        {
            set
            {
                variance = value;
            }
            get
            {
                return variance;
            }
        }

        public double CropSize
        {
            set
            {
                cropSize = value;
            }
            get
            {
                return cropSize;
            }
        }

        #endregion

        public NormalDistributionGenerator() : base(0, 1)
        {
            r = new Random(this.GetHashCode()); //bug 6911: constructor without parameter makes all generators not really random
        }

        public override object getValueFromGetter(int getterN)
        {
            switch (getterN)
            {
                case 0:
                    double result;
                    do
                    {
                        result = Variance * Math.Sqrt(-2 * Math.Log(r.NextDouble())) * Math.Cos(2 * Math.PI * r.NextDouble()) + Mean;
                    }
                    while (cropSize > 0 && (result < Mean - CropSize || result > Mean + CropSize));
                    return result;
            }
            return base.getValueFromGetter(getterN);
        }
    }
}
